package com.linkage.jz.bankruptcy.activity.Guide;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.barteksc.pdfviewer.util.Util;
import com.google.gson.Gson;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.MainActivity;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.bean.LoginInfo;
import com.linkage.jz.bankruptcy.bean.TokenInfo;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.utils.SignUtil;
import com.linkage.jz.bankruptcy.utils.Utils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


//import butterknife.Bind;
//import butterknife.ButterKnife;

/**
 * 欢迎页
 */
public class WelcomeActivity extends BaseActivity implements OnClickListener {
    private static final String TAG = WelcomeActivity.class.getSimpleName();

    ImageView ivWelcome;
    TextView jumpBtn;
    ImageView iconWelcomeIv;
    RelativeLayout bottomImg;

    boolean flag = true;


    public static void start(Context context) {
        Intent intent = new Intent(context, WelcomeActivity.class);
        context.startActivity(intent);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //全屏
        getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,
                WindowManager.LayoutParams. FLAG_FULLSCREEN);

        setContentView(R.layout.activity_welcome);

        try {
            String baseUrl = SPUtils.getInstance(Consts.SPNAME).getString("startbaseUrl");
            String links = SPUtils.getInstance(Consts.SPNAME).getString("startlinks");
            JSONArray ary = new JSONArray(links);
//            JSONArray ary = obj.getJSONArray("links");
//            imageUrls = new ArrayList<String>();
            String url = "";
            for(int i=0;i<1;i++)
            {
                JSONObject obj_str = (JSONObject)ary.get(i);

                url = obj_str.getString("picurl");
//                url = baseUrl+""+url;
//                imageUrls.add(url);



            }
            final ImageView targetImageView = (ImageView) findViewById(R.id.icon_welcome_iv);
            final String internetUrl = url;
//            runOnUiThread(new Runnable() {
//
//                @Override
//                public void run() {
//                    //更新UI
//                    Glide
//                    .with(WelcomeActivity.this)
//                    .load(internetUrl)
//                    .into(targetImageView);
//
//                }
//
//            });

            DisplayImageOptions options = new DisplayImageOptions.Builder()
                    .cacheInMemory(true)//让图片进行内存缓存
                    .cacheOnDisk(true)//让图片进行sdcard缓存
                    .showImageForEmptyUri(R.drawable.splash)//图片地址有误
                    .showImageOnFail(R.drawable.splash)//当图片加载出现错误的时候显示的图片
                    .build();
            ImageLoader.getInstance().displayImage(internetUrl,targetImageView,options);

//            new Thread(){
//                public void run(){
//                    userInfo= HttpRequest.sendGet(URL, param);
//                    Message msg = new Message();
//                    Bundle data = new Bundle();
//                    data.putString("userInfo",userInfo);
//                    msg.setData(data);
//                    handler.sendMessage(msg);
//                }
//            }.start();

//            Glide
//                    .with(WelcomeActivity.this)
//                    .load(internetUrl)
//                    .into(targetImageView);
        }catch (Exception ex)
        {
            ex.printStackTrace();
        }

        try {
            String str = SPUtils.getInstance(Consts.SPNAME).getString("userInfo");

            if (!"".equalsIgnoreCase(str)) {
                Gson gson = new Gson();
                JSONObject data = new JSONObject(str);
                String userToken = data.getString("userToken");
                SPUtils.getInstance(Consts.SPNAME).put("userToken",userToken);
                LoginInfo info = gson.fromJson(data.optString("userInfo"),LoginInfo.class);
                SPUtils.getInstance(Consts.SPNAME).put("userId",info.getId()); BankruptcyApp.loginInfo = info;
                BankruptcyApp.userToken = userToken;

            }

        }catch (Exception ex){
            ex.printStackTrace();
        }

        try{
            String tokeninfo  =SPUtils.getInstance(Consts.SPNAME).getString("tokeninfo");

            if(!"".equalsIgnoreCase(tokeninfo)) {
                Gson gson = new Gson();
                TokenInfo info = gson.fromJson(tokeninfo, TokenInfo.class);
                BankruptcyApp.tokeninfo = info;
            }

        }catch(Exception ex)
        {
            ex.printStackTrace();
        }




        ivWelcome =  (ImageView) findViewById(R.id.iv_welcome);
        jumpBtn =  (TextView) findViewById(R.id.jump_btn);
        iconWelcomeIv =  (ImageView) findViewById(R.id.icon_welcome_iv);
        getToken();
//        bottomImg =  (RelativeLayout) findViewById(R.id.bottom_img);

        //如果第一次进入引导页面

//            jumpBtn.postDelayed(new Runnable() {
//                @Override
//                public void run() {

//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
        String lversion = Utils.getLocalVersionName(WelcomeActivity.this);

                    String strName = SPUtils.getInstance(Consts.SPNAME).getString("lversion","");
                    String strCurVer = Utils.getLocalVersionName(WelcomeActivity.this);
                    if (!strCurVer.equalsIgnoreCase(strName)) {
                        SPUtils.getInstance(Consts.SPNAME).put("userToken", "");
//                BankruptcyApp.loginInfo = null;
                        BankruptcyApp.userToken = "";
                        BankruptcyApp.loginInfo = null;
                        GuideActivity.start(WelcomeActivity.this);
                        SPUtils.getInstance(Consts.SPNAME).put("lversion",strCurVer);

                        finish();
                    } else {
                        mTimer.schedule(new TimerTask() {
                            @Override
                            public void run() {

                                mHandler.sendEmptyMessage(0);
                            }
                        }, 1000, 1000);
                    }
//                        }
//                    });
                    //进入主页面或是登录页面

//                }
//            }, 3000);

        super.onCreate(savedInstanceState);
    }
    Timer mTimer = new Timer();
    int count = 3;

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            count--;
            if(count<1)
            {
                mTimer.cancel();
                if(flag) {
                    flag = false;
                    MainActivity.start(WelcomeActivity.this);
                    finish();
                }
            }else{
//                jumpBtn.setText(count+"秒后关闭");
            }
            super.handleMessage(msg);
        }

    };

    @Override
    public void initData() {

    }

    @Override
    public void initTitle() {
    }

    @Override
    public void initView() {

    }

    @Override
    public void setListener() {
        jumpBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.jump_btn:
//                MainActivity.start(this);
                //添加进入登录或是主页面
                jumpBtn.postDelayed(new Runnable() {
                    @Override
                    public void run() {
//                        finish();
                        mTimer.cancel();
                        if(flag) {
                            flag = false;
                            MainActivity.start(WelcomeActivity.this);
                            finish();
                        }
                    }
                }, 300);
                break;
            default:
                break;
        }
    }

    public void getToken()
    {

        OkHttpClient okHttpClient = new OkHttpClient();
        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";
        params.put("appid", Consts.APPID);
        params.put("nonce", rom);
        params.put("timestamp", timestamp);

        String sign = SignUtil.createSign(Consts.APPKEY,params);

        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)
                .add("sign", sign)
                .build();

        String url = Consts.WEBURL_GETTOKEN;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                Log.d(TAG, "onFailure: " + e.getMessage());
                String str = "";
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();



                String str = response.body().string();
                try{
                    JSONObject object = new JSONObject(str);
                    if(object.optInt("code") == 0)
                    {
                        Gson gson = new Gson();
                        TokenInfo info = gson.fromJson(object.optString("data"),TokenInfo.class);
                        BankruptcyApp.tokeninfo = info;
                        SPUtils.getInstance(Consts.SPNAME).put("tokeninfo",object.optString("data"));

                    }

                    str = "";
                }catch (Exception ex)
                {
                    ex.printStackTrace();
                }
            }
        });
    }

}
